// 加载系统设置 - 修复版
function loadSystemSettings() {
    showLoader();
    
    fetch('SystemSettingServlet?action=listSettings')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(responseData => {
            hideLoader();
            
            console.log("系统设置响应对象:", responseData);
            
            // 检查数据结构
            if (!responseData.success || !Array.isArray(responseData.data)) {
                throw new Error('返回数据格式不正确');
            }
            
            const settings = responseData.data;
            
            // 修复：建立字段名映射关系
            const fieldMapping = {
                'max_login_attempts': 'loginAttempts',
                'temp_password_expiry_minutes': 'tempPasswordExpiry', 
                'default_card_folder_name': 'defaultCardFolderName'
            };
            
            // 填充设置表单
            settings.forEach(setting => {
                const mappedId = fieldMapping[setting.setting_name];
                const input = document.getElementById(mappedId);
                if (input) {
                    input.value = setting.setting_value;
                    console.log(`设置 ${setting.setting_name} -> ${mappedId} = ${setting.setting_value}`);
                } else {
                    console.warn(`未找到对应的输入框: ${setting.setting_name} -> ${mappedId}`);
                }
            });
        })
        .catch(error => {
            hideLoader();
            console.error('加载系统设置失败:', error);
            showMessage('加载系统设置失败，请重试', 'error');
        });
}

// 更新系统设置 - 修复版
async function updateSystemSetting(name, value) {
    showLoader();
    
    try {
        // 使用 URLSearchParams 替代 FormData
        const params = new URLSearchParams();
        params.append('settingName', name);
        params.append('settingValue', value);
        
        const response = await fetch('SystemSettingServlet?action=update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: params
        });

        // 调试响应信息
        console.log('[DEBUG] 响应状态:', response.status);
        const responseText = await response.text();
        console.log('[DEBUG] 原始响应:', responseText);

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }

        const data = JSON.parse(responseText);
        if (!data.success) {
            throw new Error(data.message || '操作失败');
        }

        hideLoader();
        showMessage('系统设置已保存', 'success');
        
        // 延迟刷新，确保数据库已更新
        setTimeout(() => {
            loadSystemSettings();
        }, 500);
        
    } catch (error) {
        console.error('[ERROR] 请求失败:', error);
        hideLoader();
        showMessage(`更新系统设置失败: ${error.message}`, 'error');
    }
}

/**
 * 格式化后端返回的嵌套日期对象（仅日期部分）
 */
function formatBackendDate(dateObj) {
    try {
        if (!dateObj || typeof dateObj !== 'object') {
            console.warn('日期对象无效:', dateObj);
            return '未知日期';
        }     
        
        const datePart = dateObj.date;
        if (!datePart || typeof datePart !== 'object') {
            console.warn('日期数据缺失:', dateObj);
            return '日期格式错误';
        }
     
        const year = datePart.year || new Date().getFullYear();
        const month = String(datePart.month || 1).padStart(2, '0');
        const day = String(datePart.day || 1).padStart(2, '0');
        
        const formattedDate = [year, month, day].join('-');
        return formattedDate;
        
    } catch (e) {
        console.error('日期处理异常:', {
            错误: e,
            原始数据: dateObj,
            堆栈: e.stack
        });
        return '无效日期';
    }
}

// 修复后的 loadUserList 函数
function loadUserList() {
    showLoader();
    
    fetch('UserManagementServlet?action=list')
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    })
    .then(responseData => {
        console.log("完整响应对象:", responseData);
        
        // 检查数据结构
        if (!responseData.success || !Array.isArray(responseData.data)) {
            throw new Error('返回数据格式不正确');
        }
        
        const users = responseData.data;
       
        hideLoader();
        
        const adminList = document.getElementById('adminUserList');
        const userList = document.getElementById('normalUserList');
        const accountsTable = document.getElementById('accountsTableBody');
        
        // 安全检查DOM元素是否存在
        if (adminList) adminList.innerHTML = '';
        if (userList) userList.innerHTML = '';
        if (accountsTable) accountsTable.innerHTML = '';
    
        users.forEach(user => {
            // 添加到用户组管理列表
            if (adminList && userList) {
                const userItem = document.createElement('div');
                userItem.className = 'user-item';
                userItem.textContent = user.username;
                
                if (user.userType === 'ADMIN') {
                    adminList.appendChild(userItem);
                } else {
                    userList.appendChild(userItem);
                }
            }
            
            // 添加到账户列表
            if (accountsTable) {
                const row = document.createElement('tr');
                row.innerHTML = 
                    '<td>' + user.username + '</td>' +
                    '<td>' + (user.userType === 'ADMIN' ? '管理员' : '普通用户') + '</td>' +
                    '<td>' + user.status + '</td>' +
                    '<td>' + formatBackendDate(user.createdAt) + '</td>' +
                    '<td>' +
                        '<button class="btn-link reset-password" data-id="' + user.username + '" title="重置密码"><i class="fas fa-key"></i></button>' +
                        '<button class="btn-link lock-user" data-id="' + user.username + '" data-status="' + user.status + '" title="' + (user.status === 'ACTIVE' ? '锁定' : '解锁') + '">' +
                            '<i class="fas ' + (user.status === 'ACTIVE' ? 'fa-lock' : 'fa-unlock') + '"></i>' +
                        '</button>' +
                        '<button class="btn-link delete-user" data-id="' + user.userId+ '" title="删除"><i class="fas fa-trash"></i></button>' +
                    '</td>';
                
                accountsTable.appendChild(row);
            }
        });
        
        // 添加用户操作事件
        document.querySelectorAll('.reset-password').forEach(btn => {
            btn.addEventListener('click', function() {
                resetUserPassword(this.dataset.id);
            });
        });
        
        document.querySelectorAll('.lock-user').forEach(btn => {
            btn.addEventListener('click', function() {
                const userId = this.dataset.id;
                const status = this.dataset.status;
                
                if (status === 'ACTIVE') {
                    lockUser(this.dataset.id);
                } else {
                    unlockUser(this.dataset.id);
                }
            });
        });
        
        document.querySelectorAll('.delete-user').forEach(btn => {
            btn.addEventListener('click', function() {
                if (confirm('确定要删除此用户吗？')) {
                    deleteUser(this.dataset.id);
                }
            });
        });
    })
    .catch(error => {
        hideLoader();
        console.error('加载用户列表失败:', error);
        showMessage('加载用户列表失败，请重试', 'error');
    });
}


//===================== 用户添加功能 - 完整修复版 =====================
async function addUser(username, email, userType, password) {
    try {
        showLoader(); // 显示加载动画

        const params = new URLSearchParams();
        params.append('username', username);
        params.append('password', password);
        params.append('email', email);
        params.append('userType', userType || 'USER');

        console.log('[DEBUG] 请求参数:', {
            username,
            email,
            userType: userType || 'USER'
        });

        const response = await fetch('UserManagementServlet?action=add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: params
        });

        const responseText = await response.text();
        console.log('[DEBUG] 响应状态:', response.status);
        console.log('[DEBUG] 原始响应:', responseText);

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        let parsedData;
        try {
            parsedData = JSON.parse(responseText);

            // 二次解析（防止双重 JSON）
            if (typeof parsedData === 'string') {
                console.warn('[WARN] 响应是字符串，执行第二次解析');
                parsedData = JSON.parse(parsedData);
            }

            console.log('[DEBUG] 解析后的数据:', parsedData);
            console.log(`[DEBUG] success字段类型: ${typeof parsedData.success}, 值: ${parsedData.success}`);
        } catch (parseError) {
            console.error('[ERROR] JSON解析失败:', parseError);
            throw new Error('服务器响应格式错误');
        }

        if (parsedData.success === true || parsedData.success === 'true') {
            hideLoader();
            showMessage(`账户 ${username} 添加成功`, 'success');
            loadUserList();
            return true;
        } else {
            throw new Error(parsedData.message || '添加用户失败');
        }

    } catch (error) {
        console.error('[ERROR] 请求失败:', error);
        hideLoader();
        showMessage(`添加用户失败: ${error.message}`, 'error');
        return false;
    }
}



// 重置用户密码
async function resetUserPassword(username) {
    showLoader();
    
    const formData = new URLSearchParams();
    formData.append('username', username);

    fetch('UserManagementServlet?action=resetPassword', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    })
    .then(data => {
        hideLoader();
        if (data.success) {
            showMessage('密码已重置，临时密码：' + data.tempPassword + '，有效期：' + data.expiryMinutes + ' 分钟', 'success');
        } else {
            throw new Error(data.message || '重置密码失败');
        }
    })
    .catch(error => {
        hideLoader();
        console.error('重置密码失败:', error);
        showMessage('重置密码失败，请重试', 'error');
    });
}

// 锁定用户
async function lockUser(username) {
    try {
        showLoader();
        const formData = new URLSearchParams();
        formData.append('username', username);
        
        const response = await fetch('UserManagementServlet?action=lockUser', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: formData
        });

        if (!response.ok) {
            throw new Error('网络响应异常');
        }
        
        const data = await response.json();
        if (data.success) {
            updateUserStatusUI(username, 'SUSPENDED');
            showMessage('账户已成功锁定', 'success');
            loadUserList();
        } else {
            throw new Error(data.message || '锁定操作失败');
        }
    } catch (error) {
        console.error('锁定失败:', error);
        showMessage(error.message || '锁定账户失败，请重试', 'error');
    } finally {
        hideLoader();
    }
}

// 解锁用户
async function unlockUser(username) {
    try {
        showLoader();
        const formData = new URLSearchParams();
        formData.append('username', username);
        
        const response = await fetch('UserManagementServlet?action=unlockUser', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: formData
        });

        if (!response.ok) {
            throw new Error('网络响应异常');
        }
        
        const data = await response.json();
        if (data.success) {
            updateUserStatusUI(username, 'ACTIVE');
            showMessage('账户已成功解锁', 'success');
            loadSuspendedAccounts();
            loadUserList();
        } else {
            throw new Error(data.message || '解锁操作失败');
        }
    } catch (error) {
        console.error('解锁失败:', error);
        showMessage(error.message || '解锁账户失败，请重试', 'error');
    } finally {
        hideLoader();
    }
}

// 更新UI状态
function updateUserStatusUI(username, newStatus) {
    // 更新状态单元格
    const statusCells = document.querySelectorAll('.user-status[data-id="' + username + '"]');
    statusCells.forEach(cell => {
        cell.textContent = newStatus;
        cell.className = `user-status ${newStatus.toLowerCase()}`;
    });
    
    // 更新按钮状态
    const buttons = document.querySelectorAll('.lock-unlock-btn[data-id="' + username + '"]');
    buttons.forEach(btn => {
        btn.dataset.status = newStatus;
        btn.title = newStatus === 'ACTIVE' ? '锁定' : '解锁';
        const icon = btn.querySelector('i');
        if (icon) {
            icon.className = newStatus === 'ACTIVE' ? 'fas fa-lock' : 'fas fa-unlock';
        }
    });
}


//===================== 改进的删除用户功能 - 拦截外键错误版 =====================
async function deleteUser(userId) {
    try {
        showLoader();

        // 验证 userId
        if (!userId || userId === '' || userId === 'undefined') {
            throw new Error('用户ID无效');
        }

        const params = new URLSearchParams();
        params.append('userId', userId);

        console.log('[DEBUG] 删除用户参数:', { userId });

        const response = await fetch('UserManagementServlet?action=deleteUser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: params
        });

        console.log('[DEBUG] 删除用户响应状态:', response.status);

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const responseText = await response.text();
        console.log('[DEBUG] 删除用户原始响应:', responseText);

        let data;
        try {
            data = JSON.parse(responseText);
        } catch (parseError) {
            console.error('[ERROR] JSON解析失败:', parseError);
            throw new Error('服务器响应格式错误');
        }

        if (data && data.success && data.success !== false) {
            hideLoader();
            loadUserList();
            loadSuspendedAccounts(); // 同时刷新挂起账户列表
            showMessage('用户已删除', 'success');
        } else {
            let errorMessage = data.message || '删除用户失败';

            // 更友好的错误信息提示
            if (
                errorMessage.includes('当前登录') ||
                errorMessage.includes('cannot delete') ||
                errorMessage.toLowerCase().includes('foreign key') ||
                errorMessage.includes('外键') ||
                errorMessage.includes('约束')
            ) {
                errorMessage = '该用户有关联数据（如名片夹等），无法删除';
            } else if (errorMessage.includes('不存在')) {
                errorMessage = '用户不存在或已被删除';
            }

            throw new Error(errorMessage);
        }

    } catch (error) {
        hideLoader();
        console.error('[ERROR] 删除用户失败:', error);
        showMessage(`删除用户失败: ${error.message}`, 'error');
    }
}


//===================== 改进的用户列表渲染（确保userId正确传递）=====================
function renderUserListWithCorrectIds(users) {
    const adminList = document.getElementById('adminUserList');
    const userList = document.getElementById('normalUserList');
    const accountsTable = document.getElementById('accountsTableBody');
    
    // 安全检查DOM元素是否存在
    if (adminList) adminList.innerHTML = '';
    if (userList) userList.innerHTML = '';
    if (accountsTable) accountsTable.innerHTML = '';

    users.forEach(user => {
        // 确保userId存在且有效
        const userId = user.userId || user.user_id || user.id;
        const username = user.username || '';
        
        console.log('[DEBUG] 渲染用户:', {userId, username}); // 调试输出
        
        // 添加到用户组管理列表
        if (adminList && userList) {
            const userItem = document.createElement('div');
            userItem.className = 'user-item';
            userItem.textContent = username;
            
            if (user.userType === 'ADMIN') {
                adminList.appendChild(userItem);
            } else {
                userList.appendChild(userItem);
            }
        }
        
        // 添加到账户列表
        if (accountsTable && userId) {
            const row = document.createElement('tr');
            row.innerHTML = 
                '<td>' + username + '</td>' +
                '<td>' + (user.userType === 'ADMIN' ? '管理员' : '普通用户') + '</td>' +
                '<td>' + (user.status || 'ACTIVE') + '</td>' +
                '<td>' + formatBackendDate(user.createdAt) + '</td>' +
                '<td>' +
                    '<button class="btn-link reset-password" data-id="' + username + '" title="重置密码">' +
                        '<i class="fas fa-key"></i>' +
                    '</button>' +
                    '<button class="btn-link lock-user" data-id="' + username + '" data-status="' + (user.status || 'ACTIVE') + '" title="' + (user.status === 'ACTIVE' ? '锁定' : '解锁') + '">' +
                        '<i class="fas ' + (user.status === 'ACTIVE' ? 'fa-lock' : 'fa-unlock') + '"></i>' +
                    '</button>' +
                    '<button class="btn-link delete-user" data-id="' + userId + '" data-username="' + username + '" title="删除">' +
                        '<i class="fas fa-trash"></i>' +
                    '</button>' +
                '</td>';
            
            accountsTable.appendChild(row);
        }
    });
    
    // 重新绑定删除事件（确保使用正确的userId）
    document.querySelectorAll('.delete-user').forEach(btn => {
        btn.addEventListener('click', function() {
            const userId = this.dataset.id;
            const username = this.dataset.username;
            
            console.log('[DEBUG] 删除按钮点击:', {userId, username});
            
            if (confirm(`确定要删除用户 "${username}" 吗？`)) {
                deleteUser(userId);
            }
        });
    });
    
    // 其他事件绑定...
    bindOtherUserEvents();
}

// ===================== 绑定其他用户相关事件 =====================
function bindOtherUserEvents() {
    // 重置密码事件
    document.querySelectorAll('.reset-password').forEach(btn => {
        btn.addEventListener('click', function() {
            resetUserPassword(this.dataset.id);
        });
    });
    
    // 锁定/解锁用户事件
    document.querySelectorAll('.lock-user').forEach(btn => {
        btn.addEventListener('click', function() {
            const username = this.dataset.id;
            const status = this.dataset.status;
            
            if (status === 'ACTIVE') {
                lockUser(username);
            } else {
                unlockUser(username);
            }
        });
    });
}

// 渲染挂起账户列表（状态不为ACTIVE的用户）
function loadSuspendedAccounts() {
    // 显示加载指示器
    const suspendedLoader = document.createElement('div');
    suspendedLoader.className = 'loader';
    suspendedLoader.innerHTML = `
        <div class="loader-spinner"></div>
        <p>正在加载挂起账户列表...</p>
    `;
    const suspendedBody = document.getElementById('suspendedAccountsBody');
    if (suspendedBody) {
        suspendedBody.innerHTML = '';
        suspendedBody.parentNode.insertBefore(suspendedLoader, suspendedBody);
    }
    
    // 调用真实API获取用户数据
    fetch('UserManagementServlet?action=list')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(responseData => {
            // 移除加载指示器
            console.log("suspended响应对象:", responseData);
            suspendedLoader.remove();
            
            // 检查数据结构
            if (!responseData.success || !Array.isArray(responseData.data)) {
                throw new Error('返回数据格式不正确');
            }
            
            const allUsers = responseData.data;
            
            // 筛选非活跃用户
            const suspendedUsers = allUsers.filter(user => {
                return user.status && user.status.toUpperCase() !== 'ACTIVE';
            });
            
            // 清空现有内容
            if (suspendedBody) {
                suspendedBody.innerHTML = '';
                
                if (suspendedUsers.length === 0) {
                    suspendedBody.innerHTML = `<tr><td colspan="4" style="text-align: center;">没有挂起的账户</td></tr>`;
                    return;
                }
                
                // 填充非活跃用户列表
                suspendedUsers.forEach(user => {
                    const row = document.createElement('tr');
                    
                    // 确定状态显示文本
                    let statusText = '已挂起';
                    if (user.status === 'LOCKED') {
                        statusText = '已锁定';
                    } else if (user.status === 'SUSPENDED') {
                        statusText = '已挂起';
                    } else if (user.status === 'PENDING_DELETE') {
                        statusText = '待删除';
                    }
                    
                    row.innerHTML = 
                        '<td>' + user.username + '</td>' +
                        '<td>' + statusText + '</td>' +
                        '<td>' + formatBackendDate(user.createdAt) + '</td>' +
                        '<td class="action-buttons">' +
                            '<button class="btn-link unlock-btn" data-id="' + user.username + '" title="解除挂起">' +
                                '<i class="fas fa-lock-open"></i> 解除' +
                            '</button>' +
                            '<button class="btn-link delete-btn" data-id="' + user.userId + '" title="删除账户">' +
                                '<i class="fas fa-trash"></i> 删除' +
                            '</button>' +
                        '</td>';
                    
                    suspendedBody.appendChild(row);
                });
                
                // 添加操作按钮事件监听器
                bindSuspendedAccountEvents();
            }
        })
        .catch(error => {
            // 移除加载指示器
            suspendedLoader.remove();
            
            console.error('加载挂起账户失败:', error);
            if (suspendedBody) {
                suspendedBody.innerHTML = `
                    <tr>
                        <td colspan="4" style="text-align: center; color: #e74c3c;">
                            加载失败: ${error.message || '未知错误'}
                        </td>
                    </tr>
                `;
            }
        });
}

// 绑定挂起账户事件
function bindSuspendedAccountEvents() {
    document.querySelectorAll('.unlock-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const username = this.getAttribute('data-id');
            unlockUser(username);
        });
    });
    
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const userId = this.getAttribute('data-id');
            if (confirm('确定要删除此账户吗？')) {
                deleteUser(userId);
            }
        });
    });
}

// 辅助函数：HTML转义
function escapeHtml(text) {
    if (typeof text !== 'string') return text;
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}